import { IMgr } from "./IMgr";


export class EventMgr implements IMgr{

    init() {
    }
    finit() {
    }

    private eventMap: Map<string, { callBack: Function, thiz: any }[]> = new Map();

    on(eventId: string, callBack: Function, thiz: any): void {
        let array = this.eventMap.get(eventId);
        if (!array) {
            array = [];
            this.eventMap.set(eventId, array);
        }
        array.push({
            callBack,
            thiz
        });
    }

    off(eventId: string, callBack: Function, thiz: any): void {
        let array = this.eventMap.get(eventId);
        if (array) {
            for (let i = 0; i < array.length; i++) {
                if (array[i].callBack == callBack && array[i].thiz == thiz) {
                    array.splice(i, 1);
                    break;
                }
            }
        }
    }

    dispatch(eventId: string, ...args: any) {
        let array = this.eventMap.get(eventId);
        if (array) {
            for (let i = 0; i < array.length; i++) {
                try {
                    args = args || [];
                    args.unshift(eventId);
                    (array[i].callBack as Function).apply(array[i].thiz, args);
                } catch (e) {
                    console.error("dispatch event error.. ", e);
                }
            }
        }
    }
}
